package com.everest.tribalapp;




import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity
{

	private Button login;
	private EditText user;
	private EditText pwd;
	protected String user1;
	protected String pwd1;
	public String url;
	private CheckBox checkbox;
	private String u="";
	private String p="";
	private int c=0;
	private Survey_Desk_Account account;
	protected String u1;
	protected String p1;
	public ProgressDialog pd;

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Login.this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);
		user=(EditText)findViewById(R.id.login_username);
		pwd=(EditText)findViewById(R.id.login_password);
		login=(Button)findViewById(R.id.login_sigin);
		checkbox=(CheckBox)findViewById(R.id.login_remember);
		 account=new Survey_Desk_Account(getApplicationContext());
		resume();
		login.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				
				user1=user.getText().toString().trim();
				try {
					user1=URLEncoder.encode(user1,"UTF-8");
					System.out.println(user1);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				pwd1=pwd.getText().toString().trim();
				if((!user1.isEmpty())&&(!pwd1.isEmpty()))
				{
					boolean a;
					a=online();
					if(a)
					{
						if(checkbox.isChecked())
						{
							System.out.println("clicked");
							SharedPreferences preferences=getSharedPreferences("log",MODE_PRIVATE);
							SharedPreferences.Editor editor=preferences.edit();
							editor.putString("user",user1);
							editor.putString("pwd",pwd1);
							editor.putInt("checked",1);
							editor.commit();
						}
						else
						{
							SharedPreferences preferences=getSharedPreferences("log",MODE_PRIVATE);
							SharedPreferences.Editor editor=preferences.edit();
							editor.putString("user",user1);
							editor.putString("pwd",pwd1);
							editor.putInt("checked",0);
							editor.commit();
						}
				    new Check().execute();
					}
					
					else
					{
//						Toast.makeText(getApplicationContext(), "Check UR Internet",Toast.LENGTH_SHORT).show();
						
						account.openToRead();
						int i=account.getRowCount();
						account.close();
						if(i==0)
						{
							Toast.makeText(getApplicationContext(), "login using Internet for first time",Toast.LENGTH_SHORT).show();
							
						}
						else
						{
							account.openToRead();
							u1=account.MyUser().toString().trim();
							p1=account.MyPwd().toString().trim();
							account.close();
							if((user1.equals(u1))&&(pwd1.equals(p1)))
							{
								Global.username=user1;
								Intent intent=new Intent(getApplicationContext(),Home.class);
								startActivity(intent);
								Login.this.finish();
							}
							else
							{
								Toast.makeText(getApplicationContext(), "Username/Password Not Match",Toast.LENGTH_SHORT).show();
									
							}
						}
					}
				}
				else
				{
					Toast.makeText(getApplicationContext(), "Some Field is missing",Toast.LENGTH_SHORT).show();
					
				}
				// TODO Auto-generated method stub
				
			}
		});
	}
class Check extends AsyncTask{

	
	private String json;
	private JSONObject jsonobject;
	private String code;
	private String msg;
	@Override
	protected void onPreExecute() 
	{
		super.onPreExecute();
		pd = new ProgressDialog(Login.this);
//		pd.setTitle("Please Wait...");
	  pd.setMessage("Loading..");
		pd.setCancelable(false);
		pd.show();
		url=Global.login_url+user1+"&password="+pwd1;
		System.out.println(url);
		Global.username=user1;
	}

	@Override
	protected Object doInBackground(Object... params) {
		
		try 
		{
			json=JSONfunctions.getStringContent(url);
			jsonobject=new JSONObject(json);
			code=jsonobject.getString("code");
			msg=jsonobject.getString("msg");
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
	}
	@Override
	protected void onPostExecute(Object result)
	{
		super.onPostExecute(result);
		pd.dismiss();
		if(code.equalsIgnoreCase("1"))
		{
			account.openToWrite();
			account.deleteAll();
			account.insert(user1, pwd1);
			account.close();
			Intent intent=new Intent(getApplicationContext(),Home.class);
			startActivity(intent);
			Login.this.finish();
		}
		else
		{
			Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
		}
		
	}

}

public void resume()
{
	SharedPreferences preferences=getSharedPreferences("log",MODE_PRIVATE);
	u=preferences.getString("user","");
	p=preferences.getString("pwd","");
	c=preferences.getInt("checked",0);
	if(c==1){
	user.setText(u);
	pwd.setText(p);
	checkbox.setChecked(true);
	}
}

public boolean online()
{
	ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo ni=cm.getActiveNetworkInfo();
	if(ni != null && ni.isConnected())
	{
		return true;
	}
	return false;
	
}
}
